package com.jsn.buildbase.weather.ui.widget

import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.View
import android.widget.LinearLayout
import android.widget.Scroller
import androidx.core.view.NestedScrollingParent
import androidx.core.view.ViewCompat
import com.jsn.baselibx.utils.Logs
import com.jsn.buildbase.home.dp


@Suppress("DEPRECATED_IDENTITY_EQUALS", "DEPRECATION")
@SuppressLint("ViewConstructor")
class Parent ( context: Context, attributes: AttributeSet):LinearLayout(context,attributes),NestedScrollingParent {

    val scoller:Scroller

    //change it to custom height
    val headHeight :Int=300.dp

    init {
        scoller= Scroller(context)
    }

    override fun computeScroll() {
        if(scoller.computeScrollOffset()){
            scrollTo(0, scoller.getCurrY());
            invalidate()
        }
    }

    override fun onNestedScrollAccepted(child: View, target: View, axes: Int) {
        Logs.e("nested scroll started")
    }

    override fun onStartNestedScroll(child: View, target: View, axes: Int): Boolean {
        return nestedScrollAxes and ViewCompat.SCROLL_AXIS_VERTICAL !== 0
    }


    override fun onNestedPreScroll(target: View, dx: Int, dy: Int, consumed: IntArray) {
        Log.e("", "onNestedPreScroll")
        val hiddenTop = dy > 0 && scrollY < headHeight
        val showTop =
            dy < 0 && scrollY >= 0 && !ViewCompat.canScrollVertically(target, -1)

        if (hiddenTop || showTop) {
            scrollBy(0, dy)
            consumed[1] = dy
        }
    }


    /*if(scrollY>=headHeight) return false
    if(scrollY<=0){
        return false
    }
    fling(velocityY.toInt())
    invalidate()
    return true*/

    fun fling(velocityY: Int) {
        scoller.fling(0, scrollY, 0, velocityY, 0, 0, 0, headHeight)
        invalidate()
    }


    override fun scrollTo(x: Int, y: Int) {
        var dest:Int=0
        if (y < 0)
        {
            dest = 0
        }
        if (y > headHeight)
        {
            dest = headHeight
        }
        if (dest != getScrollY()) {
            super.scrollTo(x, dest);
        }
    }


}